<!-- 环境设计 -->
<template>
    <div class="environ-designe-wrapper">
        <Button type="primary" @click="openDesignModal" :disabled="disabledAllBtn">环境设计</Button>
        <Modal
            v-model="designModal.show"
            :title="designModal.title"
            @on-ok="createProject"
            :width="600"
            :loading="designModal.loading"
            class="drawer-low-modal"
        >
            <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="85">
                <FormItem label="使用内置模板" prop="internal">
                    <RadioGroup v-model="formValidate.internal" @on-change="changeInternal">
                        <Radio :label="1">是</Radio>
                        <Radio :label="0">否</Radio>
                    </RadioGroup>
                </FormItem>
                <!-- <FormItem label="内置类型" prop="typeId" v-if="formValidate.internal === 1">
                    <Select filterable
                        v-model="formValidate.typeId"
                        @on-change="handChangeSelectType"
                        placeholder="请选择"
                    >
                        <Option v-for="type in typeRecordData" :key="type.id" :value="type.id">{{
                            type.value
                        }}</Option>
                    </Select>
                </FormItem> -->
                <FormItem
                    :label="formValidate.internal === 0 ? '创建方式' : '选择模板'"
                    prop="tmplId"
                    class="template-lable"
                >
                    <Button
                        v-if="formValidate.internal === 1"
                        type="primary"
                        class="template-type w150"
                        :ghost="true"
                        @click="refreshTem('research')"
                    >
                        内置模板
                    </Button>
                    <div class="template-select-wrapper" v-if="formValidate.internal === 0">
                        <Select filterable
                            v-model="edit.curSelectType"
                            @on-change="handChangeSelectType"
                            placeholder="请选择"
                        >
                            <Option
                                v-for="type in edit.templateSelectType"
                                :key="type.value"
                                :value="type.value"
                                >{{ type.title }}</Option
                            >
                        </Select>
                        <!-- <div class="select-type-wrapper">
                            <div
                                class="type"
                                v-for="type in edit.templateSelectType"
                                :key="type.value"
                                :class="edit.curSelectType === type.value ? 'current' : ''"
                                @click="handChangeSelectType(type.value)"
                            >
                                {{ type.title }}
                            </div>
                        </div> -->
                        <div class="select-content-wrapper">
                            <template v-if="edit.curSelectType === 'projectTemplate'">
                                <Button
                                    type="primary"
                                    class="template-type w150"
                                    :ghost="edit.curTemplateType === '0' ? false : true"
                                    @click="refreshTem('0')"
                                >
                                    普通模板
                                </Button>
                                <Button
                                    type="primary"
                                    class="template-type w150"
                                    :ghost="edit.curTemplateType === 'base' ? false : true"
                                    @click="refreshTem('base')"
                                >
                                    基础模板
                                </Button>
                            </template>
                            <template v-if="edit.curSelectType === 'image'">
                                <GenerateTemplate @on-success="getTemplateInfo"></GenerateTemplate>
                            </template>
                            <template v-if="edit.curSelectType === 'exper'">
                                <ExperTemplate @on-select="getTemplateInfo"></ExperTemplate>
                            </template>
                            <template v-if="edit.curSelectType === 'upload'">
                                <ImportTemplate @on-success="getTemplateInfo"></ImportTemplate>
                            </template>
                            <template v-if="edit.curSelectType === 'project'">
                                <Button
                                    type="primary"
                                    class="template-type w150"
                                    ghost
                                    @click="showProjectDrawer()"
                                >
                                    选择工程
                                </Button>
                            </template>
                            <template v-if="edit.curSelectType === 'topo'">
                                创建空白环境后，请在工作台拓扑模块点击自定义编辑进入拓扑编辑页面，编辑完成后需保存科研
                                <!--<TopoTemplate @on-success="getTemplateInfo"></TopoTemplate>-->
                            </template>
                        </div>
                    </div>
                    <!-- <Button type="primary" ghost @click="refreshTem()">选择</Button> -->
                    <div class="chose-wrap" v-show="formValidate.tmplName || formValidate.projectName">
                        <div class="flex" style="flex: auto">
                            <!--  <img src="../../../assets/globalIcon/template.png" class="chose-s-icon" /> -->
                            <Icon type="logo-buffer" :size="16" />
                            <div class="chose-name">{{ formValidate.tmplName || formValidate.projectName}}</div>
                        </div>
                        <img
                            src="../../../assets/globalIcon/dis-del.png"
                            style="width: 13px; height: 14px; cursor: pointer"
                            @click="clearTemp"
                        />
                    </div>
                </FormItem>
            </Form>
        </Modal>
         <!--工程模板-->
         <DrawerPage
            select
            v-model="addDeviceModel"
            :title="edit.curTemplateType === 'research' ? '内置模板' : '工程模板'"
            :closable="true"
            :mask-closable="false"
            width="1000"
            :columns="getTemplateCol()"
            :data="templateList"
            :total="templateTotal"
            :page.sync="templatePage"
            :size.sync="templatePageSize"
            @queryFun="toPlateTabs()"
        >
        <!--   @change-page="temOnChange" -->
            <template slot="search">
                <Select filterable
                    v-if="edit.curTemplateType === 'research'"
                    v-model="searchTemType"
                    @on-change="changeTemType"
                    placeholder="请选择内置类型"
                    clearable
                    filterable
                >
                    <Option v-for="type in typeRecordData" :key="type.id" :value="type.id">{{
                        type.value
                    }}</Option>
                </Select>
                <Select filterable
                    v-if="edit.curTemplateType !== 'research'"
                    clearable
                    placeholder="请选择可见范围"
                    v-model="selectProTemModel"
                    @on-change="changeTemplate"
                >
                    <Option value="public">系统</Option>
                    <Option value="share">单位</Option>
                    <Option value="private">个人</Option>
                </Select>
                <Input
                    v-model.trim="searchTemNameInput"
                    placeholder="模板名称"
                    clearable
                    @on-change="searchTemNameBtn"
                />
                <Button
                    class="header-btn"
                    type="primary"
                    @click="refreshTem(edit.curTemplateType,true)"
                    ><i class="el-icon-refresh-right"
                /></Button>
            </template>
        </DrawerPage>
        <Modal v-model="desModal.show" :z-index="4000" :width="800" title="描述" footer-hide class-name="fix-height-modal">
            <div v-html="desModal.content" style="font-size:14px;" class="html-content ql-editor"></div>
        </Modal>
        <TemplateDetailModal :z-index="4000" ref="templateDetailModal"></TemplateDetailModal>
        <!--工程列表-->
        <DrawerPage
        select
        v-model="projectDrawer.show"
        title="工程"
        :closable="true"
        :mask-closable="false"
        width="1000"
        :columns="projectCol"
        :data="projectList"
        :total="projectTotal"
        :page.sync="queryProject.pageIndex"
        :size.sync="queryProject.pageSize"
        @queryFun="getProjectList"
    >
        <template slot="search">
            <!-- <Select filterable
                v-if="edit.curTemplateType === 'research'"
                v-model="searchTemType"
                @on-change="changeTemType"
                placeholder="请选择内置类型"
                clearable
                filterable
            >
                <Option v-for="type in typeRecordData" :key="type.id" :value="type.id">{{
                    type.value
                }}</Option>
            </Select> -->
            <Input
                v-model.trim="queryProject.name"
                placeholder="工程名称"
                clearable
                @on-change="debounceSearchProject"
            />
            <Button
                class="header-btn"
                type="primary"
                @click="refreshProject()"
                ><i class="el-icon-refresh-right"
            /></Button>
        </template>
    </DrawerPage>
    </div>
</template>
<script>
import PageLayout from '@/components/common/page';
import UploadFile from './template/upload';
import GenerateTemplate from './template/generate-template';
import ExperTemplate from './template/exper-template';
import ImportTemplate from './template/import-template';
import TopoTemplate from './template/topo-template';
import ItemUpload from '@/components/item-upload';
import TableList from '@/components/common/table-list';
import TemplateDetailModal from '../template/detail.vue'
import { updateContent } from '../api/content.js';
import { copyContentRelation } from '../api/contentRelation.js';
import { getTemplateData } from '../api/proTemplate.js';
import { creatBlankPro } from '../api/deploy.js';
import { queryTemplRelation } from '../api/templRelation.js';
import { getProjects } from '@/api/drill_compete.js'
import { typeRecordMixin } from '../mixin/research';
import { templMixin } from '../template/mixin'
import { debounce } from '@/libs/utils'
export default {
    name: 'BaseInfo',
    components: {
        UploadFile,
        GenerateTemplate,
        ImportTemplate,
        ItemUpload,
        TableList,
        PageLayout,
        ExperTemplate,
        TopoTemplate,
        TemplateDetailModal
    },
    inject: ['detailParent'],
    props: {
        // type: {
        //     type: String,
        //     default: 'template',
        // },
        // contentDetail: {
        //     type: Object,
        //     default: () => {
        //         return { id: '', name: '' };
        //     }
        // }
    },
    mixins: [typeRecordMixin,templMixin],
    data() {
        let _this = this;
        const validateTempl = (rule, value, callback) => {
            callback();
            return;
            //验证警戒值
            if (!this.formValidate.tmplId && this.edit.curSelectType !== 'topo') {
                if (this.formValidate.internal === 1) {
                    callback(new Error('请选择模板'));
                } else {
                    callback(new Error('请先选择或生成模板'));
                }
            } else {
                callback();
            }
        };
        return {
            designModal: {
                show: false,
                title: '模板选择',
                loading: true,
            },
            edit: {
                templateSelectType: [
                    {
                        title: '工程模板',
                        value: 'projectTemplate',
                    },
                    {
                        title: '镜像选择',
                        value: 'image',
                    },
                    // {
                    //     title: '科研选择',
                    //     value: 'exper',
                    // },
                    {
                        title: '导入模板',
                        value: 'upload',
                    },
                    {
                        title: '选择工程',
                        value: 'project',
                    },
                    {
                        title: '新建空白环境',
                        value: 'topo',
                    },
                ],
                curSelectType: 'projectTemplate',
                curTemplateType: 0,
            },
            resource: {
                tool: 1,
                document: 2,
                video: 3,
            },
            formValidate: {
                internal: 1,
                typeId: '',
                tmplId: '',
                tmplName: '',
                projectId:'',
                projectName:''
            },
            ruleValidate: {
                internal: [
                    {
                        type: 'number',
                        required: true,
                        trigger: 'change',
                        message: '请选择',
                    },
                ],
                typeId: [
                    {
                        required: true,
                        trigger: 'change',
                        message: '请选择内置类型',
                    },
                ],
                tmplId: [
                    {
                        required: true,
                        trigger: 'change',
                        validator: validateTempl,
                    },
                ]
                // tmplName: [
                //     {
                //         required: true,
                //         trigger: 'change'
                //     }
                // ]
            },
            // allContentRelation: [],
            // 工程模板
            addDeviceModel: false,
            templatePage: 1,
            templatePageSize: 14,
            templateTotal: 0,
            templateList: [],
            errorPic:{},
            templateCol: [
                {
                    type: 'index',
                    width: 60,
                    align: 'left',
                },
                {
                    title: '模板名称',
                    key: 'name',
                    align: 'left',
                    tooltip:true
                },
                {
                    title: '可见范围',
                    key: 'visibility',
                    align: 'left',
                    render: (h, params) => {
                        return h(
                            'div',
                            {
                                style: {
                                    color: this.handlePublic(params.row.visibility).color,
                                },
                            },
                            this.handlePublic(params.row.visibility).text
                        );
                    },
                },
                {
                    title: '类型',
                    key: 'typeName',
                    placement: 'top-left',
                    width: 200,
                    tooltip: true,
                },
                {
                    type:'html',
                    title: '描述',
                    key: 'description',
                    align: 'left',
                    render: (h, params) => {
                        return h('span', {
                            domProps: {
                                innerHTML: params.row.description.replace(/\<br\>/g, '')
                            },
                            class:'html-line text-ellipsis',
                            on:{
                                click:(e) => {
                                    this.desModal.show = true;
                                    this.desModal.content = params.row.description;
                                }
                            }
                        });
                    }
                },
                {
                    title:'Topo缩略图',
                    key:'picUrl',
                    render:(h,params) => {
                            let dis = !params.row.picUrl || params.row.picUrl.indexOf('files') === -1
                            return h('div',{
                                style:{
                                    'width': '50px',
                                    'height': '28px',
                                    'display': 'flex',
                                    'justify-content':'center',
                                    'align-items': 'center',
                                    'overflow': 'hidden'
                                }
                            },[
                                h('img',{
                                    attrs:{
                                        src:params.row.picUrl
                                    },
                                    style:{
                                        'max-height':dis ? '100%' : '78px',
                                        'cursor':dis ? '' : 'zoom-in'
                                    },
                                    on:{
                                        error:(e) => {
                                            params.row.picUrl = this.defImg
                                            e.target.style.maxHeight = '100%';
                                            e.target.style.cursor = '';
                                            return this.setDefImg(e)
                                        },
                                        click:(e) => {
                                            if(dis || params.row.dis || e.target.style.maxHeight === '100%'){
                                                return
                                            }
                                            this.$refs.templateDetailModal.showModal(e)
                                        }
                                    }
                                })
                            ])
                        }
                },
                {
                    title: '设计者',
                    key: 'creatorName',
                    align: 'left',
                },
                // {
                //     title: '创建时间',
                //     key: 'created',
                //     minWidth: 120,
                //     align: 'left'
                // },
                {
                    title: '操作',
                    key: 'actionCustom',
                    align: 'left',
                    width: 120,
                    render: (h, params) => {
                        let tempUserFlag;
                        let listMatchId = params.row.matchId || params.row.id;
                        let storeMatchId =
                            this.formValidate.templRelationId || this.formValidate.tmplId;
                        tempUserFlag = listMatchId === storeMatchId;
                        let text = '';
                        if (tempUserFlag) {
                            text = '已用';
                        } else {
                            text = '使用';
                        }
                        // let status = this.getResourceDisStatus(
                        //     params.row.visibility === 'private',
                        //     params.row.creator
                        // );
                        //						(this.formValidate.public == 1 || !this.isOwn) && params.row.visibility == 'private'
                        return h(
                            'a',
                            {
                                style: {
                                    //								'display': 'flex',
                                    //								'justify-content': 'flex-start',
                                    //								'align-items': 'center',
                                    color: tempUserFlag ? '#2d8cf0' : '#515a6e',
                                    // cursor: tempUserFlag ? 'not-allowed' : 'pointer'
                                },
                            },
                            [
                                h(
                                    'div',
                                    {
                                        on: {
                                            click: () => {
                                                if (tempUserFlag) {
                                                    //this.$Message.warning('单位的课件不允许选择个人资源');
                                                    return;
                                                }
                                                this.chooseTemp(params);
                                            },
                                        },
                                        style: {
                                            //									'margin-left': '15px',
                                        },
                                    },
                                    [
                                        h('img', {
                                            attrs: {
                                                src: tempUserFlag
                                                    ? require('../../../assets/globalIcon/choosed.png')
                                                    : require('../../../assets/globalIcon/add.png'),
                                            },
                                            style: {
                                                'margin-right': '5px',
                                                'vertical-align': 'middle',
                                                width: '16px',
                                                height: '16px',
                                                display: 'inline-block',
                                            },
                                        }),
                                        h('span', {}, text),
                                    ]
                                ),
                            ]
                        );
                    },
                },
            ],
            searchTemplateName: '',
            proTemLoading: false,
            searchTemNameInput: '',
            selectProTemModel: '',
            templateVisibility: '',
            desModal:{
                show:false,
                content:''
            },
            projectList:[],
            projectTotal:0,
            queryProject:{
                pageIndex:1,
                pageSize:10
            },
            projectDrawer:{
                show:false,
                title:'工程列表'
            },
            projectCol: [
                {
                    title: '名称',
                    key: 'name',
                    minWidth: 200,
                    tooltip: true
                },
                // {
                //     title: '是否为分布式',
                //     key: 'type',
                //     show: this.$store.state.common.showDistributed,
                //     filter: (type) => {
                //         return type == 'distributed'
                //             ? '是'
                //             : '否';
                //     },
                //     setColor: (type) => {
                //         return type == 'distributed' ? 'var(--status-yes)' : 'var(--status-no)';
                //     },
                //     minWidth: 60
                // },
                {
                    title:'虚拟机数量',
                    key:'vmCount',
                    tooltip: true,
                    minWidth: 60
                },
                {
                    title:"创建者",
                    key: 'creatorName',
                    tooltip: true,
                    minWidth: 100
                },
                {
                    title:"创建时间",
                    key: 'created',
                    tooltip: true,
                    minWidth: 135
                },
                {
                    title: '操作',
                    key: 'action',
                    align: 'left',
                    width: 120,
                    render: (h, params) => {
                        let tempUserFlag;
                        let listMatchId = params.row.id;
                        let storeMatchId = this.formValidate.projectId;
                        tempUserFlag = listMatchId === storeMatchId;
                        let text = '';
                        if (tempUserFlag) {
                            text = '已用'
                        } else {
                            text = '使用'
                        }
                        // let status = this.getResourceDisStatus(
                        //     params.row.visibility === 'private',
                        //     params.row.creator
                        // );
                        //						(this.formValidate.public == 1 || !this.isOwn) && params.row.visibility == 'private'
                        return h(
                            'a',
                            {
                                style: {
                                    //								'display': 'flex',
                                    //								'justify-content': 'flex-start',
                                    //								'align-items': 'center',
                                    color: tempUserFlag ? '#2d8cf0' : '#515a6e',
                                    // cursor: tempUserFlag ? 'not-allowed' : 'pointer'
                                },
                            },
                            [
                                h(
                                    'div',
                                    {
                                        on: {
                                            click: () => {
                                                if (tempUserFlag) {
                                                    //this.$Message.warning('单位的课件不允许选择个人资源');
                                                    return;
                                                }
                                                this.chooseProject(params.row);
                                            },
                                        },
                                        style: {
                                            //									'margin-left': '15px',
                                        },
                                    },
                                    [
                                        h('img', {
                                            attrs: {
                                                src: tempUserFlag
                                                    ? require('../../../assets/globalIcon/choosed.png')
                                                    : require('../../../assets/globalIcon/add.png'),
                                            },
                                            style: {
                                                'margin-right': '5px',
                                                'vertical-align': 'middle',
                                                width: '16px',
                                                height: '16px',
                                                display: 'inline-block',
                                            },
                                        }),
                                        h('span', {}, text),
                                    ]
                                ),
                            ]
                        );
                    }
                },
            ]
        };
    },
    computed: {
        disModifyTemplate() {
            return (
                this.contentDetail.deployStatus &&
                ![0, 10].includes(this.contentDetail.deployStatus)
            );
        },
        contentDetail() {
            return this.detailParent.contentDetail;
        },
        contentId() {
            return this.contentDetail.id;
        },
        disabledAllBtn(){
            return this.detailParent.disabledAllBtn
        },
    },
    watch: {
        contentDetail: {
            handler(val) {
                let { tmplId, tmplName, templRelationId } = this.contentDetail;
                this.formValidate.tmplId = tmplId;
                this.formValidate.tmplName = tmplName;
                this.formValidate.templRelationId = templRelationId;
            },
        },
    },
    created() {
        this.queryTypeRecordAll();
        this.setStyle();
    },
    mounted() {},
    methods: {
        getTemplateCol() {
            if (this.edit.curTemplateType === 'research') {
                return this.templateCol.filter((item) => item.title !== '可见范围');
            } else {
                return this.templateCol.filter(item => item.title !== '内置类型');
            }
        },
        // 设置高度
        setStyle() {
            window.fullHeight = document.documentElement.clientHeight;
            window.fullWidth = document.documentElement.clientWidth;
            this.fullHeight = window.fullHeight;
            this.fullWidth = window.fullWidth;
            this.setUserTableHei = this.fullHeight - 212;
        },
        openDesignModal(data) {
            this.designModal.show = true;
            // this.contentDetail = data;
            this.$refs.formValidate.resetFields();
            let { tmplId, tmplName, id, templRelationId } = this.contentDetail;
            if (!id) {
                return;
            }
            this.formValidate.tmplId = tmplId;
            this.formValidate.tmplName = tmplName;
            this.formValidate.templRelationId = templRelationId;
        },
        changeInternal(val) {
            //改变是否使用内置模板
            this.formValidate.typeId = '';
            this.formValidate.tmplId = '';
            this.formValidate.tmplName = '';
            this.formValidate.templRelationId = '';
            this.formValidate.projectId = '';
            this.formValidate.projectName = '';
            this.$refs.formValidate.resetFields();
            this.formValidate.internal = val;
            this.edit.curSelectType = 'projectTemplate';
        },
        cancelLoading() {
            this.designModal.loading = false;
            setTimeout(() => {
                this.designModal.loading = true;
            });
        },
        // 创建工程，并绑定工程与案例关联关系，关系绑定完成后，跳转至拓扑图页面
        createProject() {
            if (!this.formValidate.tmplId && this.edit.curSelectType !== 'topo' && this.edit.curSelectType !== 'project') {
                this.$Message.error('请先选择或生成模板');
                this.cancelLoading();
                return;
            }
            this.$refs.formValidate.validate((valid) => {
                if (valid) {
                    if(this.edit.curSelectType  === 'project'){
                        let data = {
                            projectId: this.formValidate.projectId,
                            tmplId: '',
                            tmplName: '',
                            typeId: '',
                            internal: this.formValidate.internal
                        };
                        updateContent(this.contentId, data)
                            .then(({ code, message }) => {
                                if (code !== 1) {
                                    this.$Message.warning(message);
                                    return;
                                }
                                this.designModal.show = false;
                                this.$emit('ok');
                                this.detailParent && this.detailParent.getContentDetail();
                            })
                            .catch(() => {
                                this.$Message.error('修改科研信息异常');
                            })
                            .finally(() => {
                                this.cancelLoading();
                                resolve();
                            });
                        return 
                    }
                    let tmplId = this.formValidate.tmplId;
                    return new Promise((resolve) => {
                        creatBlankPro(
                            this.edit.curSelectType !== 'topo' && tmplId ? tmplId : '',
                            {
                                mode: 'complete',
                                name: this.contentDetail.name,
                                quotaTypeId: '2',
                                trainId: 0,
                                type: 'normal',
                            },
                            'complete'
                        )
                            .then(data => {
                                let { code, message, attribute } = data;
                                if (![1, 2].includes(code)) {
                                    // 成功或导入中均不需要报错
                                    this.$Message.warning(message);
                                    this.cancelLoading();
                                    return;
                                }
                                let result = attribute.result;
                                data = {
                                    projectId: result.id,
                                    tmplId: this.formValidate.tmplId,
                                    tmplName: this.formValidate.tmplName,
                                    typeId: this.formValidate.typeId,
                                    internal: this.formValidate.internal
                                };
                                if (this.formValidate.internal === 1) {
                                    //内置模板
                                    data.templRelationId = this.formValidate.templRelationId; //内置模板关联id
                                }
                                if (this.copyContentId) {
                                    copyContentRelation({
                                        newContentId: this.contentId,
                                        oldContentId: this.copyContentId,
                                    }).then(({ code, data, message }) => {
                                        if (code === 1) {
                                            // 复制成功之后创新
                                            this.detailParent && this.detailParent.refreshDocInfo();
                                        }
                                    });
                                }
                                updateContent(this.contentId, data)
                                    .then(({ code, message }) => {
                                        if (code !== 1) {
                                            this.$Message.warning(message);
                                            return;
                                        }
                                        this.designModal.show = false;
                                        this.$emit('ok');
                                        this.detailParent && this.detailParent.getContentDetail();
                                    })
                                    .catch(() => {
                                        this.$Message.error('修改科研信息异常');
                                    })
                                    .finally(() => {
                                        this.cancelLoading();
                                        resolve();
                                    });
                            })
                            .catch(() => {
                                this.$Message.error('创建拓扑图异常');
                                this.cancelLoading();
                                resolve();
                            });
                    });
                } else {
                    this.cancelLoading();
                }
            });
        },
        getResourceDisStatus(isPrivate, creator) {
            let isNotOwn = !(this.USER_ID == this.formValidate.createUserId || this.isCreate);
            let isNotCommonCreator = this.formValidate.createUserId !== creator && !this.isCreate;
            return (this.formValidate.public == 1 || (isNotOwn && isNotCommonCreator)) && isPrivate;
        },
        chooseTemp(params) {
            if (params.row.tempUserFlag) {
                this.$Message.info({
                    content: '已使用该模板！',
                    duration: 3,
                });
            } else {
                let _index = params.row._index;
                for (let i = 0; i < this.templateList.length; i++) {
                    this.templateList[i].tempUserFlag = false;
                }
                this.$set(this.templateList[_index], 'tempUserFlag', true);
                this.getTemplateInfo(params.row);
                // this.formValidate.envtempid = params.row.name;
                // this.useTemplateId = params.row.id;
                //存储模板可见范围
                this.useTempVisibility = params.row.visibility;
            }
        },
        getTemplateInfo(info) {
            if (this.disModifyTemplate) {
                this.$Message.warning('请先销毁环境');
                return;
            }
            this.formValidate.tmplId = info.id;
            this.formValidate.templRelationId = info.matchId; //内置模板与模板的关联Id
            this.formValidate.tmplName = info.name;
            this.formValidate.typeId = info.typeId;
            if (this.edit.curSelectType === 'exper') {
                this.copyContentId = info.contentId;
            } else {
                this.copyContentId = '';
            }
            //存储模板可见范围
            this.useTempVisibility = 'private';
            // this.updateContent(); //确定再保存
        },
        chooseProject(data){
            if (data.tempUserFlag) {
                this.$Message.info({
                    content: '已使用该工程！',
                    duration: 3,
                });
            } else {
                let _index = data._index;
                for (let i = 0; i < this.projectList.length; i++) {
                    this.projectList[i].tempUserFlag = false;
                }
                this.$set(this.projectList[_index], 'tempUserFlag', true);
                this.formValidate.projectId = data.id;
                this.formValidate.projectName = data.name;
            }
        },
        // 更新模板信息
        updateContent() {
            updateContent(this.contentId, this.formValidate)
                .then(({ code, message }) => {
                    if (code === 1) {
                        this.$Message.info('修改模板信息成功');
                        let { tmplId, tmplName } = this.formValidate;
                        this.detailParent.updateDetail({ tmplId, tmplName });
                    } else {
                        this.$Message.error(message);
                    }
                })
                .catch((error) => {});
        },
        handChangeSelectType(val) {
            this.edit.curSelectType = val;
            if(val === 'project' || val === 'topo'){
                this.formValidate.templId = '';
                this.formValidate.templName = '';
            }else{
                this.formValidate.projectId = '';
                this.formValidate.projectName = '';
            }
        },
        clearTemp() {
            this.formValidate.tmplId = '';
            this.formValidate.tmplName = '';
            this.copyContentId = '';
            // this.updateContent();
        },
        // 选择工程模板
        toPlateTabs(type) {
            this.addDeviceModel = true;
            this.templateList = [];
            let params = {
                pageIndex: this.templatePage,
                pageSize: this.templatePageSize,
            };
            let data = {
                name: this.searchTemplateName,
                visibility: this.templateVisibility,
                type: 'project',
                markType: this.edit.curTemplateType,
            };
            this.proTemLoading = true;
            let reqApi;
            if (this.edit.curTemplateType === 'research') {
                reqApi = queryTemplRelation({
                    ...params,
                    typeId: this.searchTemType,
                    templName: this.searchTemplateName,
                });
            } else {
                reqApi = getTemplateData(data, params);
            }
            reqApi
                .then(async ({code, data: { items, total }, message }) => {
                    if (code === 1) {
                        this.templateTotal = Number(total);
                        if(this.edit.curTemplateType === 'research'){
                            let pArr = items.map(item => {
                                return this.getTempInfpByID(item.templId).then(data => {
                                    item.picUrl = data.picUrl
                                }).catch(() => {
                                    item.picUrl = ''
                                })
                            })
                            await Promise.all(pArr);
                        }
                        for (let i = 0; i < items.length; i++) {
                            items[i].tempUserFlag = false;
                            items[i].matchId = items[i].id; //使用已用匹配
                            if (this.edit.curTemplateType === 'research') {
                                //内置模板
                                items[i].matchId = items[i].id; //使用已用匹配
                                items[i].name = items[i].templName;
                                items[i].id = items[i].templId;
                                items[i].typeName = this.handleTypeRecord(items[i].typeId);
                                if (items[i].id === this.formValidate.templRelationId) {
                                    items[i].tempUserFlag = true;
                                }
                            } else {
                                if(items[i].picUrl){
                                    items[i].picUrl = `/files${items[i].picUrl}`
                                }
                                if (items[i].id === this.formValidate.tmplId) {
                                    items[i].tempUserFlag = true;
                                }
                            }
                        }
                        this.templateList = items;
                    } else {
                        this.templateList = [];
                        this.templateTotal = 0;
                    }
                    this.proTemLoading = false;
                })
                .catch((err) => {
                    this.proTemLoading = false;
                    console.log(err);
                });
        },
        temOnChange(val) {
            this.templatePage = val;
            this.toPlateTabs();
        },
        changeTemplate(val) {
            this.templatePage = 1;
            this.templateVisibility = val;
            this.toPlateTabs();
        },
        changeTemType(){
            this.templatePage = 1;
            this.toPlateTabs();
        },
        searchTemNameBtn(val) {
            this.templatePage = 1;
            this.searchTemplateName = this.searchTemNameInput;
            this.toPlateTabs();
        },
        refreshTem(type,isRefresh) {
            // if(type === 'research' && !this.formValidate.typeId){
            //     this.$Message.info('请先选择内置类型');
            //     return
            // }
            this.templateList = [];
            this.edit.curTemplateType = type;
            this.templatePage = 1;
            this.searchTemplateName = '';
            this.searchTemNameInput = '';
            this.searchTemType = '';
            this.templateVisibility = '';
            this.selectProTemModel = '';
            this.toPlateTabs();
        },
        closeDistribution() {
            this.addDeviceModel = false;
        },
        handlePublic(val) {
            let obj = {
                text: '',
                color: '#8d95a6',
            };
            switch (val) {
                case 'private':
                case 0:
                case '0':
                    return (obj = {
                        text: '个人',
                        color: 'rgb(255, 165, 0)',
                    });
                    break;
                case 'share':
                case 1:
                case '1':
                    return (obj = {
                        text: '单位',
                        color: 'rgb(50, 205, 50)',
                    });
                    break;
                case 'public':
                case 2:
                case '2':
                    return (obj = {
                        text: '系统',
                        color: 'rgb(65, 105, 225)',
                    });
                    break;
            }
        },
        showProjectDrawer(){
            this.projectDrawer.show = true;
            this.refreshProject();
        },
        // 获取工程列表
        getProjectList() {
            let params = {...this.queryProject}
            if (this.isRootDesigner) {
                params.enableAll = true;
            }
            getProjects(params).then((data) => {
                if (data.code == 1) {
                    this.projectList = data.data.items;
                } else {
                    this.$Message.error(data.message);
                }
            });
        },
        debounceSearchProject:debounce(function(){
            this.getProjectList();
        },500),
        refreshProject(){
            this.queryProject = {
                pageIndex:1,
                pageSize:10,
                status:3
            }
            this.getProjectList();
        },
    },
};
</script>
<style scoped>
.w150 {
    width: 150px;
}
.select-content-wrapper {
    margin-top: 20px;
}
.select-type-wrapper {
    display: flex;
    justify-content: space-between;
    height: 32px;
    --checkbox-active-bgcolor: #3a3ad1;
    --checkbox-btn-checked-color: #fff;
    /* width: 360px; */
    border: 1px solid var(--checkbox-active-bgcolor);
}
.select-type-wrapper .type {
    flex: 1;
    text-align: center;
    background: #fff;
    border-right: 1px solid var(--checkbox-active-bgcolor);
    color: var(--checkbox-active-bgcolor);
    cursor: pointer;
}
.select-type-wrapper .type.current {
    background: var(--checkbox-active-bgcolor);
    color: var(--checkbox-btn-checked-color);
}
.select-type-wrapper .type:last-child {
    border-right: none;
}

.chose-wrap {
    display: flex;
    justify-content: space-between;
    padding: 3px 8px;
    background-color: rgb(245, 248, 255);
    align-items: center;
    margin-top: 10px;
}
.chose-name {
    width: 300px;
    display: inline-block;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.chose-image {
    display: inline-block;
    height: 32px;
    width: auto;
    vertical-align: middle;
}
.del-icon {
    width: 13px;
    height: 14px;
    cursor: pointer;
}

.drawer-title {
    font-size: 14px;
    font-weight: 700;
}
</style>
